from urllib import request,parse
import json,time,hashlib

def getSalt():
	return str(time.time()*1000)

def getSign(keywords,salt):
	sign = "fanyideskweb" + keywords + salt + "sr_3(QOHT)L2dx#uuGR@r"
	str_md5 = hashlib.md5()
	str_md5.update(sign.encode('utf-8'))
	sign = str_md5.hexdigest()
	return sign
url = "https://fanyi.youdao.com/translate_o?smartresult=dict&smartresult=rule"

def translate(key):
	salt = getSalt()
	sign = getSign(key,salt)

	# 定义请求的参数，并编码转换
	data = {
		'i':key,
		'from':'AUTO',
		'to':'AUTO',
		'smartresult':'dict',
		'client':'fanyideskweb',
		'salt':salt,
		'sign':sign,
		'doctype':'json',
		'version':'2.1',
		'keyfrom':'fanyi.web',
		'action':'FY_BY_REALTIME',
		'typoResult':'false',
	}
	data = parse.urlencode(data)

	#设置hearders头信息
	headers={
		'Content-Length':len(data),
		'Accept':'application/json, text/javascript, */*; q=0.01',
		# 'Accept-Encoding':'gzip, deflate, br',
		'Accept-Language':'zh-CN,zh;q=0.9,en;q=0.8',
		'Cookie':'OUTFOX_SEARCH_USER_ID=-160023884@10.168.1.241; OUTFOX_SEARCH_USER_ID_NCOO=1057327125.5699296; JSESSIONID=aaaGkRTmGZEDr7QHds7Cw; ___rl__test__cookies=1542887853313',
		'Host':'fanyi.youdao.com',
		'Origin':'http://fanyi.youdao.com',
		'Referer':'http://fanyi.youdao.com/',
		'User-Agent':'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36',
		'X-Requested-With':'XMLHttpRequest',
	}
	#创建请求，发送请求，爬取信息
	req = request.Request(url,data=bytes(data,encoding="utf-8"),headers=headers)
	res = request.urlopen(req)

	# 解析结果
	str_json = res.read().decode("utf-8")
	# print(str_json)
	myjson = json.loads(str_json)

	print('-------result------\r\n' + myjson['translateResult'][0][0]['tgt'] + '\r\n-------------\r\n')
# print(myjson['data'])

if __name__ == '__main__':
	while True:
		key = input('请输入想要翻译的内容:')
		if(key == 'quit'):
			exit()
		else:
			translate(key)